import { ApiDict } from "_common/api/sys";
import { PageParams } from "_common/DataType";
import { SysDict } from "_common/entity";
import { AxiosInstance } from "axios";
import classnames from "classnames";
import { TableTitle } from "components";
import React, { useState, useEffect, useMemo } from "react";
import { RefreshIcon, SearchIcon } from "tdesign-icons-react";
import {
  Button,
  Input,
  Popconfirm,
  PrimaryTableCol,
  Row,
  Space,
  Table,
  message,
} from "tdesign-react";
import DictDrawer from "./DictDrawer";
type DictTableProp = {
  children: boolean;
  parentId?: number;
  onRowClick?: (value: number) => void;
  axios: AxiosInstance;
  className?: string;
};
const DictTable: React.FC<DictTableProp> = (props: DictTableProp) => {
  const { children, onRowClick, parentId, axios, className } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([
    1, 2,
  ]);
  const [loading] = useState<boolean>(false);
  const [DictList, setDictList] = useState<SysDict[]>([]);
  const [selectedRow, setSelectedRow] = useState<SysDict>();
  const [dictName, setDictName] = useState<string>();
  const [pageState, setPageState] = useState<PageParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });

  // const { loading, contractList, current, pageSize, total } = pageState;
  const [visible, setVisible] = useState(false);
  const [edit, setEdit] = useState(false);
  const apiDict = new ApiDict(axios);
  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
    if (!children) {
      onRowClick?.(value[0] as number);
    }
  }

  useEffect(() => {
    getDictList();
  }, [dictName, parentId]);

  const getDictList = async () => {
    const response = await apiDict.getPageList({
      ...pageState,
      parentId,
      children,
      label: dictName,
    });
    if (response && response.code == 200 && response.data) {
      setDictList(response.data.list);
      setPageState({
        ...pageState,
        total: response.data.total,
      });
    }
  };

  // 删除用户
  const deleteDict = async (id: number) => {
    const response = await apiDict.deleteDict(id);
    if (response && response.code === 200 && response.data) {
      message.success("删除成功");
      getDictList();
    }
  };

  const columns: PrimaryTableCol<SysDict>[] = useMemo(() => {
    const arr: PrimaryTableCol<SysDict>[] = [];
    if (!children) {
      arr.push({
        colKey: "row-select",
        type: "single",
        // 允许单选(Radio)取消行选中
        checkProps: { allowUncheck: true },
        width: 50,
      });
    }
    arr.push(
      {
        align: "left",
        width: 100,
        ellipsis: true,
        colKey: "index",
        title: "序号",
        cell: ({ rowIndex }) => {
          let _index =
            (pageState.pageNum - 1) * pageState.pageSize + rowIndex + 1;
          return <span>{_index}</span>;
        },
      },
      {
        align: "left",
        ellipsis: true,
        colKey: "dictLabel",
        title: "字典名称",
      },
      {
        align: "left",
        ellipsis: true,
        colKey: "dictCode",
        title: "字典编码",
      },
      {
        align: "left",
        ellipsis: true,
        colKey: "dictValue",
        title: "字典值",
      },
      {
        align: "center",
        fixed: "right",
        width: 150,
        colKey: "op",
        title: "操作",
        cell({ row }) {
          return (
            <Space size={0}>
              <Button
                theme="success"
                variant="text"
                onClick={() => {
                  setVisible(true);
                  setEdit(true);
                  setSelectedRow(row);
                }}
              >
                编辑
              </Button>
              <Popconfirm
                content="确认删除吗"
                destroyOnClose
                placement="top"
                showArrow
                theme="danger"
                onConfirm={() => deleteDict(row.id)}
              >
                <Button theme="danger" variant="text">
                  删除
                </Button>
              </Popconfirm>
            </Space>
          );
        },
      }
    );
    return arr;
  }, [children]);

  return (
    <div className={classnames(className)}>
      <Row justify="space-between" className="mb-4">
        <div className="flex flex-row justify-between mb-4">
          <TableTitle text="字典列表" />
          <Space size={5}>
            <Input
              suffixIcon={<SearchIcon />}
              placeholder="请输入要搜索的字典名称"
              onChange={(v) => {
                setDictName(v);
              }}
            />
            <Button
              onClick={() => {
                if (children && !parentId) {
                  message.error("请先选择父级字典");
                  return;
                }
                setVisible(true);
                setEdit(false);
              }}
            >
              添加字典
            </Button>
            <Button
              icon={<RefreshIcon />}
              variant="outline"
              onClick={() => {
                getDictList();
              }}
            ></Button>
          </Space>
        </div>
      </Row>

      <Table<SysDict>
        bordered
        columns={columns}
        loading={loading}
        data={DictList}
        rowKey="id"
        selectedRowKeys={selectedRowKeys}
        verticalAlign="middle"
        hover
        lazyLoad
        selectOnRowClick={true}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: pageState.pageSize,
          total: pageState.total,
          current: pageState.pageNum,
          showJumper: true,
          onCurrentChange(current) {
            setPageState({
              ...pageState,
              pageNum: current,
            });
          },
          onPageSizeChange(size) {
            setPageState({
              ...pageState,
              pageSize: size,
            });
          },
        }}
      />
      <DictDrawer
        open={visible}
        axios={axios}
        edit={edit}
        value={selectedRow}
        parentId={parentId}
        isChildren={children}
        onSuccess={() => {
          setVisible(false);
          getDictList();
        }}
      />
    </div>
  );
};
export default DictTable;
